/**
 * @Author: 安广伟
 * @Email: anguangwei@jwzh.tech
 * @Date: 2024-09-10 14:29:36
 * @LastEditTime 2024-09-10 14:29:36
 * @since: 1.0.0
 * @Version: 1.0.0
 * @Description:
 */

package com.ry.mall.server.interceptor;

import com.ry.mall.server.aspect.watch.TimedOperation;
import com.ry.mall.server.common.constant.RedisConstant;
import com.ry.mall.server.controller.TokenTimeOutException;
import com.ry.mall.server.util.AuthContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Service
public class TokenLoginAttributeInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @TimedOperation(summary = "拦截器判断 token", description = " 拦截器对当前的 http request 进行拦截。以判断 token 中是否包含有效的用户信息！ ")
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
                             @Nullable Object handler)
            throws TokenTimeOutException {
        // 检查请求头中是否存在token属性
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            // 不存在时，抛出特定的 Exception，让重定向到登录页面或其他处理逻辑
            throw new TokenTimeOutException();
        }

        String wxUserId = String.valueOf(redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token));
        if (StringUtils.isEmpty(wxUserId)) {
            // wxUserId 为空时，抛出特定的 Exception，让重定向到登录页面或其他处理逻辑
            throw new TokenTimeOutException();
        }
        AuthContextHolder.setUserId(wxUserId);
        return true; // 存在则允许请求继续执行
    }

    // 其他两个方法可以根据需求实现，这里默认为空即可
    @Override
    public void postHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
                           @NonNull Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
                                @NonNull Object handler, @Nullable Exception ex)
            throws Exception {
    }

}
